package com.venn.util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;

/**
 * Created by venn on 4/9/2018.
 */
public class HdfsUtil {

    public static boolean isPathExist(String filePath) throws IOException {

        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(filePath), conf);
        Path path = new Path(filePath);
        if (fs.exists(path)) {
            return true;
        }

        return false;
    }

    public static boolean deletePath(String path) throws IOException {

        Configuration conf = new Configuration();
        FileSystem deletFs = FileSystem.get(URI.create(path), conf);
        Path delef = new Path(path);

        if (deletFs.delete(delef, true)) {
            return true;
        }
        return false;
    }

    /**
     * 输入mr的输出路径，如果存在，删除
     * @param outputPath
     * @return
     * @throws IOException
     */
    public static boolean handleOutPutPath(String outputPath) throws IOException {

        if (HdfsUtil.isPathExist(outputPath)) {
            if (HdfsUtil.deletePath(outputPath)) {
                System.out.println("Output path "+outputPath+" exists, Delete output path success.");
            } else {
                System.out.println("Delete output path "+outputPath+" fail.");
                System.exit(1);
            }
        }
        return true;
    }
}
